package cool.taomu.toolkit.utils

import java.net.InetAddress
import java.net.SocketTimeoutException
import java.time.Duration
import org.apache.commons.net.ntp.NTPUDPClient
import org.apache.commons.net.ntp.TimeInfo
import org.slf4j.LoggerFactory

/**
 * https://gitee.com/iproject/MyTools2/blob/dev/tools2/src/main/java/com/taomus/mytools/utils/ntp/DateNTPUtils.java
 */
class NTPUtils {
	val LOG = LoggerFactory.getLogger(NTPUtils);
	val static String HOST = "";

	def currentTimeMillis() {
	}

	def ntpCurrentTimeMillis() {
		// logger.info("get ntp current time millis");
		if (HOST.indexOf(",") == -1) {
			// logger.info(DEFAULT_HOST);
			var NTPUDPClient nuc = new NTPUDPClient();
			var InetAddress ia;
			ia = InetAddress.getByName(HOST);
			nuc.setDefaultTimeout(Duration.ofMillis(500));
			var TimeInfo timeInfo = nuc.getTime(ia);
			return timeInfo.getMessage().getOriginateTimeStamp().getTime();
		} else {
			var String[] hosts = HOST.split(",");
			for (String host : hosts) {
				try {
					// logger.info(host);
					var NTPUDPClient nuc = new NTPUDPClient();
					nuc.setDefaultTimeout(Duration.ofMillis(500));
					var InetAddress ia;
					ia = InetAddress.getByName(host);
					var TimeInfo timeInfo = nuc.getTime(ia);
					return timeInfo.getMessage().getOriginateTimeStamp().getTime();
				} catch (SocketTimeoutException e) {
					// logger.error("TimeoutException ",e);
				}
			}
		}
		return System.currentTimeMillis();

	}
}
